package com.example.presentshopping.ui.activity

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseMvpActivity
import com.example.presentshopping.config.base.MyApplication.getContext
import com.example.presentshopping.config.bean.AlipayBean
import com.example.presentshopping.config.bean.DetailsBean
import com.example.presentshopping.config.bean.LocationBean
import com.example.presentshopping.config.bean.OrdermlyBean
import com.example.presentshopping.jpay.JPay
import com.example.presentshopping.jpay.JPay.JPayListener
import com.example.presentshopping.mvp.presenter.PublicPresenter
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL
import com.example.presentshopping.net.http.HttpURL.Req_alipay
import com.example.presentshopping.net.http.HttpURL.Req_orderPlatform
import com.example.presentshopping.net.observer.TaskCallback
import com.example.presentshopping.ui.custom.PayPwdEditText
import com.example.presentshopping.utils.ToastUtil
import com.example.presentshopping.utils.glide.GlideUtil
import com.example.presentshopping.utils.tool.GsonUtils
import com.tencent.mm.opensdk.utils.Log
import kotlinx.android.synthetic.main.activity_ordermly.*
import org.greenrobot.eventbus.EventBus
import java.text.DecimalFormat

//创建订单
class OrdermlyActivity : BaseMvpActivity() {

    var goods_id: String? = null
    var is_team: String? = null
    var team_type: String? = null
    var number: String? = null
    var detailsBean: DetailsBean? = null
    var details: String? = null

    var order_id: String? = null
    var aliPayBean : AlipayBean?=null

    var iinit: LocationBean.DataBean.ListBean? = null

    var LocationID: String? = null
    var locationbean: LocationBean? = null

    var ordermlyBean: OrdermlyBean? = null

    private var queryInfoPresenter: PublicPresenter? = null
    var pay = 2
    private var walletDialog: Dialog? = null

    var  activitys :String ?=null
    override val layoutId: Int
        get() = R.layout.activity_ordermly

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        queryInfoPresenter = PublicPresenter(this, true, "加载中...")
        queryInfoPresenter?.attachView(this)
        title_main_tv.leftBackImageTv.setOnClickListener { finish() }

        goods_id = intent.getStringExtra("goods_id")
        is_team = intent.getStringExtra("is_team")
        team_type = intent.getStringExtra("team_type")
        details = intent.getStringExtra("detailsBean")
        number = intent.getStringExtra("number")
        activitys = intent.getStringExtra("activity")

        detailsBean = GsonUtils.getGson().fromJson(details, DetailsBean().javaClass)
        Log.e("OrdermlyActivity", "" + detailsBean?.data?.id)
        GlideUtil.load(this, detailsBean?.data?.thumb, myodtunb)
        title_tv.text = detailsBean?.data?.title
        market_tv.text = "¥:  " + detailsBean?.data?.marketprice
        number_tv.text = "数量：$number"
        if(activitys?.contains("ProductListFragment")!!){
            //click_nowPay.visibility = View.GONE
        }

        marketpricetv.text ="应付："+"¥ " +DecimalFormat("#0.00").format((detailsBean?.data?.marketprice?.toDouble()?.times(number?.toInt()!!)))
        dialog_spec_select_ok.setOnClickListener {

            if (LocationID != null) {
                if (order_id == null) {
                    establishOd(
                        goods_id!!,
                        is_team!!,
                        number!!,
                        team_type!!,
                        LocationID.toString(),
                        ""
                    )


                } else {
                    when (pay) {
                        1 -> {
                            showEditPayPwdDialog()
                        }
                        2 -> {
                            Orderalipay(order_id!!)
                        }
                    }
                }

            } else {
                showToast("请选择地址")
            }

        }

        addressname.setOnClickListener {
            val inite = Intent(this, SelectaddressActivity().javaClass)
            startActivityForResult(inite,666) }


             click_nowPay.setOnClickListener {
            is_nowPay.visibility = View.VISIBLE
            is_alipay.visibility = View.GONE
            pay = 1
        }
        click_alipay.setOnClickListener {
            is_nowPay.visibility = View.GONE
            is_alipay.visibility = View.VISIBLE
            pay = 2
        }

    }




    override fun onResume() {
        gainLocation()
        super.onResume()
    }
    override fun onDestroy() {
        queryInfoPresenter?.detachView()
        super.onDestroy()
    }

    override fun showToast(msg: String?) {
       ToastUtil.showMsg(msg)
    }

    override fun onSuccess(data: String?) {

    }

    override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {

    }

    //获取默认地址
    fun gainLocation() {
        queryInfoPresenter?.netWorkRequestPost(HttpURL.Req_getAddressList,
            HttpRequest.getGoodsDetail(
                ""
            ),
            object : TaskCallback {
                @SuppressLint("SetTextI18n")
                override fun onSuccess(data: String?) {
                    locationbean = GsonUtils.getGson().fromJson(data, LocationBean().javaClass)
                    if (locationbean?.data?.list != null) {
                        for (iinit in locationbean?.data?.list!!) {
                            if (iinit.status == 1) {
                                LocationID = iinit?.id.toString()
                                addressname.text =
                                    "收件人: " + iinit.linkman + "\n" + "电话:  " + iinit.tel + "\n" + "地址:  " + iinit.address
                            }
                        }
                    }


                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {

                }

            })
    }

    //创建订单
    fun establishOd(
        goods: String,
        team: String,
        number: String,
        team_ty: String,
        address: String,
        remark: String
    ) {
        queryInfoPresenter?.netWorkRequestPost(HttpURL.Req_getcreateOrder,
            HttpRequest.createOrder(goods, team, number, team_ty, address, remark),
            object : TaskCallback {
                override fun onSuccess(data: String?) {
                    ordermlyBean = GsonUtils.getGson().fromJson(data, OrdermlyBean().javaClass)
                    order_id = ordermlyBean?.data?.order_id

                    when (pay) {
                        1 -> {
                            showEditPayPwdDialog()
                        }
                        2 -> {
                            Orderalipay(order_id!!)
                        }
                    }
                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {
                 showToast(msg)
                }

            })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

    }

    //平台支付
    fun showEditPayPwdDialog() {
        val view: View = layoutInflater.inflate(R.layout.dialog_layout, null)
        walletDialog = Dialog(this, R.style.walletFrameWindowStyle)
        walletDialog!!.setContentView(
            view, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        )

        val window = walletDialog!!.window
        val wl = window!!.attributes

        //紧贴软键盘弹出
        wl.gravity = Gravity.BOTTOM
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT
        walletDialog!!.onWindowAttributesChanged(wl)
        walletDialog!!.setCanceledOnTouchOutside(false)
        walletDialog!!.show()


        //忘记密码 按钮
        view.findViewById<View>(R.id.tv_forgetPwd).setOnClickListener {
            startActivity(
                Intent(
                    this@OrdermlyActivity,
                    SetupPayPwdCheckActivity::class.java
                )
            )
        }
        val ppet: PayPwdEditText = view.findViewById(R.id.dialog_ppet)
        val img_cancle = view.findViewById<ImageView>(R.id.img_cancle)
        //调用initStyle方法创建你需要设置的样式
        //调用initStyle方法创建你需要设置的样式
        ppet.initStyle(R.drawable.edit_num_bg, 6, 0.33f, R.color.gray, R.color.black, 30)
        img_cancle.setOnClickListener {
            walletDialog!!.dismiss()
            //手动收起软键盘
            val imm =
                getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(ppet.windowToken, 0)
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)

        }

        ppet.setOnTextFinishListener {
            //密码输入完后的回调
            walletDialog!!.dismiss()
            //手动收起软键盘
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(ppet.windowToken, 0)
            //可在此执行下一步操作
            val paypass = ppet.pwdText
            order_id?.let { it1 -> orderPlat(it1, paypass) }

        }
        //延迟弹起软键盘，使PayPwdEditText获取焦点
        Handler().postDelayed({ ppet.setFocus() }, 100)

    }

    //支付宝
    fun Orderalipay(orderid: String) {
        queryInfoPresenter?.netWorkRequestPost(
            Req_alipay,
            HttpRequest.orderalipay(orderid),
            object : TaskCallback {
                override fun onSuccess(data: String?) {
                    aliPayBean =GsonUtils.getGson().fromJson(data,AlipayBean().javaClass)
                    aliPay(aliPayBean?.data!!)
                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {

                }

            })
    }

    //平台支付
    fun orderPlat(orderid: String, password: String) {
        queryInfoPresenter?.netWorkRequestPost(Req_orderPlatform, HttpRequest.orderPlatform(
            orderid,
            password
        ), object : TaskCallback {
            override fun onSuccess(data: String?) {
                if (is_team?.contains("1")!!){
                    showToast(" 成功加入拼团队列！")
                }else {
                    showToast("支付成功！")
                }

                MainActivity.toStartActivity(this@OrdermlyActivity)
                finish()
            }

            override fun onFailure(
                e: Throwable?,
                code: Int,
                msg: String?,
                isNetWorkError: Boolean
            ) {
                showToast(msg)
            }

        })
    }

    private fun aliPay(orderInfo: String) { // 支付宝支付
        JPay.getIntance(this).toPay(JPay.PayMode.ALIPAY, orderInfo, object : JPayListener {

            override fun onPaySuccess(resultStatus: String?) {
                MainActivity.toStartActivity(this@OrdermlyActivity)
                finish()
            }

            override fun onPayError(error_code: Int, message: String) {
                showToast("支付失败")
              //  finish()
            }

            override fun onPayCancel() {
                showToast("取消了支付")
              //  finish()
            }
        })
    }
   fun hideKeyboard(){
       val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
       if(imm.isActive){
           if (this.currentFocus?.windowToken != null) {
              imm.hideSoftInputFromWindow(currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS);
               }
       }
       imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
   }

}